<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>layout 后台大布局 - 手机信息查询</title>
    <link rel="stylesheet" href="/leek_bbs/statics/yu-ui/js_css/yu.css">
    <link rel="stylesheet" href="/leek_bbs/statics/layui/css/layui.css">
    <style>

        a { color:blue; transition:0.5s; }
        a:hover { color:red; }
        .layui-layout-admin .layui-footer{
            left: 0px;
            width: 98%;
        }
    </style>

</head>
<body style="background-color: #F2F2F2">

<div class="layui-layout layui-layout-admin" id="hmc">

    <div style="background-color: #FFFFFF">
        <!-- 内容主体区域 -->
        <div class="layui-tab layui-tab-brief" lay-filter="demo" lay-allowClose="true" >
            <div class="layui-tab-content">
                <div class="layui-tab-item layui-show">
                    <form class="layui-form">
                        <div class="layui-form-item marg">
                            <div class="layui-inline">
                                <label class="layui-form-label layui-input-inline">账号查询:</label>
                                <div class="layui-input-inline">
                                    <input type="text" id="userName" placeholder="账号..." name="title" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label layui-input-inline">手机查询:</label>
                                <div class="layui-input-inline">
                                    <input type="text" id="phone" name="phone" placeholder="手机..." autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">状态查询:</label>
                                    <div class="layui-input-block">
                                        <select name="userStatus" id="userStatus" lay-verify="required">
                                            <option value=""></option>
                                            <option value="0">禁用</option>
                                            <option value="1">正常</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item marg">
                            <label class="layui-form-label layui-input-inline">别名查询:</label>
                            <div class="layui-inline">
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" id="anotherName" name="anotherName" placeholder="别名...">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label layui-input-inline">注册时间查询:</label>
                                <div class="layui-input-inline">
                                    <input type="text" class="layui-input" id="test10" placeholder="注册时间范围...">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <div class="layui-input-inline layui-col-xs-offset3">
                                    <button type="button" data-type="search" id="search" class="layui-btn layui-btn-warm layui-icon layui-icon-search">查询</button>
                                    <button type="reset" class="layui-btn layui-icon layui-icon-refresh-1 layui-btn-normal">重置</button>
                                </div>
                            </div>
                        </div>
                    </form>

                    <table class="layui-hide" id="searchReload" lay-filter="test"></table>

                    <!-- 自定义按钮 -->
                    <div style="display: none;" id="cellphoneToo">
                        <div class="layui-btn-group">
                            <button type="button" class="layui-btn layui-btn-sm" lay-event="add">增加</button>
                           <!-- <button type="button" class="layui-btn layui-btn-sm" lay-event="batchDelete">批量删除</button>-->
                        </div>
                    </div>

                    <!-- 自定义操作按钮 -->
                    <div id="cellphoneBar" >
                  <!--      <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>-->
                        <a class="layui-btn layui-btn-xs stateCut" style="background-color: rgb(188, 23, 32);" lay-event="userStateCut" >禁用</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="resetPassword" >重置密码</a>
                        <a class="layui-btn layui-btn-xs" lay-event="addRole" >添加角色</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-footer">
        <!-- 底部固定区域 -->
        <div align="center">
            © 凛冬 - 版权所有
        </div>

    </div>
</div>
<script src="/leek_bbs/statics/component/common_import.js"></script>

<script>
    var tableLoad;
    let roles;
    let role_id = 1;
    getRoles();
    layui.use(['table','element','laydate','form'], function(){
        var table = layui.table;
        var element = layui.element;
        var laydate = layui.laydate;
        var form = layui.form;

        //日期时间范围
        laydate.render({
            elem: '#test10'
            ,type: 'datetime'
            ,range: '~'
            ,done: function(value, date, endDate){
                console.log(value); //得到日期生成的值，如：2017-08-18
                console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            }
        });
        //表格数据渲染必须函数
        tableLoad = table.render({
                elem: '#searchReload'	//表格操作对象
                ,url:'/leek_bbs/stair/userManage/getUserInfo'	//数据接口
                //,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                ,toolbar: '#cellphoneToo'	//自定义表格上面左侧按钮
                , method: 'post'
                , contentType: 'application/json'
                ,defaultToolbar: ['filter', 'exports',
                /*'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可

              title: '提示'
              ,layEvent: 'LAYTABLE_TIPS'
              ,icon: 'layui-icon-tips'
            }*/]
                /*,width:800
                ,height:'full-300'*/
                ,height:540     //固定表格高度,当每页要显示的条数大于10条时,让它出现下拉框
                ,cellMinWidth:100	//设置列的最小默认宽度,拉伸时最小能缩小的宽度
                , request: {
                    pageName: 'pageCurrent' //页码的参数名称，默认：page
                    , limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                ,done:function(res,curr,count){

                    console.log();	//后台返回json数据
                    //console.log(curr);	//当前页
                    //console.log(count);	//数据总条数
                    pageCurr = curr;
                }
                //,totalRow:true	//开启合并行,进行计算

                ,text:{
                    none:'暂无相关数据'//默认:无数据
                }
                ,page: true
                //,limit:20	//设置每页显示的条数,默认显示为10条
                ,limits:[10,20,30,40]	//每页显示条数选择下拉框
                ,title: '用户信息数据表'	//数据导出标题
                /*, parseData: function (res) {     //自定义分页接收数据
                    //LayUI数据格式-尤其注意
                    return {
                        "code": 0,
                        "msg": "",
                        "count": res.length,
                        "data": res
                    }
                }*/
                ,cols: [[
                  /*  {type: 'checkbox', fixed: 'left'}	//复选框,多选*/
                     {field:'id', title:'ID',fixed: 'left', unresize: true, sort: true}//sort:已请求数据排序开启
                    ,{field:'username', title:'账号',id:'userName'}	//edit:可编辑数据 align:center居中显示
                    ,{field:'another_name', title:'别名'}
                    ,{field:'age',title:'年龄'}
                    ,{field:'sex', title:'性别'}
                    ,{field:'email', title:'邮箱'}
                   ,{field:'phone', title:'手机号码',id: 'phone'}
                    ,{field:'register_time',title:'注册时间',id:'registerTime',templet:function (d) {
                        return formDate(d.register_time)
                    }}
                    ,{field:'register_ip',title:'注册ip'}
                    ,{field:'last_login_time',title:'最后登录时间',templet:function (d) {
                        if(d.last_login_time!=null){
                            return formDate(d.last_login_time)
                        }
                        return "<span style='color: red'>暂未登录</span>"

                    }}
                    ,{field:'last_login_ip',title:'最后登录ip'}
                    ,{field:'address', title:'地址'}
                    ,{field:'profession',title:'职业'}
                    ,{field:'user_status',title:'用户状态',templet:function (d) {
                        if (d.user_status==1){
                            $(".stateCut").addClass("layui-btn-danger")
                            $(".stateCut").html("禁用")
                            return "正常"
                        }else{
                            $(".stateCut").removeClass("layui-btn-danger")
                            $(".stateCut").html("激活")
                            return "<span style='color: red'>禁止</span>"
                        }
                    }}
                    ,{fixed: 'right',width:220,title:'操作', toolbar: '#cellphoneBar'}	//toolbar可使用默认提供按钮,也可自定义按钮
                ]]
                //,id: 'Reload'     //重载标识

            });


        //表格重载
        var $ = layui.$, active = {
            search: function(){
                var userName = $('#userName').val();
                var phone = $('#phone').val();
                var anotherName = $('#anotherName').val();
                var registerTime = $('#test10').val();
                var times =registerTime.split("~");
                var beginRegister = times[0];
                var endRegister = times[1];
                var userStatus = $('#userStatus').val();
                //执行重载
                table.reload('searchReload', {
                    url: '/leek_bbs/stair/userManage/getUserInfo'
                    ,methods:"post"
                    ,request: {
                        pageName: 'pageCurrent' //页码的参数名称，默认：page
                        , limitName: 'pageSize' //每页数据量的参数名，默认：limit
                    }
                    ,page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {       //可以传对象
                        'userName': userName,
                        'phone': phone,
                        'anotherName': anotherName,
                        'beginRegister':beginRegister,
                        'endRegister':endRegister,
                        'userStatus':userStatus
                //执行重载
                    }
                }, 'data');
            }
        };
        //监听搜索按钮
        $('#search').on('click', function(){
            var type = $(this).data('type');
            console.log(type);
            active[type] ? active[type].call(this) : '';
        });


        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;    //表格选中的数据
            console.log(obj.config);
            switch(obj.event){
                case 'add':
                   // layer.alert(JSON.stringify(data));
                    addUser();
                    break;
                case 'batchDelete':
                    //layer.msg('选中了：'+ data.length + ' 个');
                    var ids = new Array(data.length);
                    for (var i in data) {
                        var id = data[i].id;
                        ids[i] = id;
                    }
                    layer.confirm('真的删除行么', function(){
                        var res;
                        deleteCellphone(ids).then(function (response) {
                            console.log(response);
                            res = response;
                            if (res == 1){
                                tableLoad.reload();
                            }
                        });
                        //刷新表格
                        /*loadTable();*/
                    });
                    break;

            };
        });

        //监听单元格编辑事件
        table.on('edit(test)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            console.log(obj.value); //得到修改后的值
            console.log(obj.field); //当前编辑的字段名
            console.log(obj.data); //所在行的所有相关数据
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            var ids = [];
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('确定删除这条数据吗', function(index){
                    ids[0] = data.id;
                    var res;
                    deleteCellphone(ids).then(function (response) {
                        res = response;
                        if (res == 1){
                            tableLoad.reload();
                        }
                    });

                });
            }else if(obj.event==='userStateCut'){
                //alert(data.id)
                //用户状态切换
                var userState;
                if (data.user_status==1){
                    userState = 0;
                }else {
                    userState=1;
                }
                updateUserState(data.id,userState);
            }else if(obj.event ==='resetPassword'){
                layer.confirm('确定重置此用户的密码吗', function(index){
                    axios.get("/leek_bbs/stair/userManage/resetPassword",{
                        params: {
                            id:data.id
                        }
                    }).then((response)=>{
                        let resdata =response.data;
                        if (resdata.code == "500020") {     //用户注册成功
                            layer.msg('<img src="/leek_bbs/statics/yu-ui/images/ui-success.png">&emsp;密码重置成功,重置密码为000000', {
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            });
                        } else {   //用户注册失败
                            layer.msg('<img src="/leek_bbs/statics/yu-ui/images/ui-error.png">&emsp;'+resdata.msg, {
                                time: 3000 //2秒关闭（如果不配置，默认是3秒）
                            });
                        }
                    })
                });
            }else if(obj.event==='addRole'){
                openAddUserRole(data);
            }
        });

        //添加角色窗口方法
        function openAddUserRole(data) {
            let index = layer.open({
                type:1
                ,title:false
                ,content:`<div id="lay-add-role" style="margin-top: 30px;">
                            <form class="layui-form" >
                            <div class="layui-form-item">
                                <label class="layui-form-label">用户名</label>
                                <div class="layui-input-inline">
                                   <input type="text" disabled="disabled" value="${data.username}" style="color: #333 !important;opacity: .6;"  name="username" lay-verify="required" autocomplete="off" class="layui-input layui-disabled">
                                </div>
                            </div>
                            <div class="layui-form-item" style="margin-top: 30px">
                                <label class="layui-form-label">角色名称</label>
                                <div class="layui-input-inline">
                                    <select lay-filter="role_name" id="role_name2" lay-verify="required">

                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item" style="margin-top: 30px">
                                <label class="layui-form-label">角色描述</label>
                                <div class="layui-input-inline">
                                    <input type="text" disabled="disabled" value="超级管理员" style="color: #333 !important;opacity: .6;"  id="role_desc2" name="role_desc" lay-verify="required" autocomplete="off" class="layui-input layui-disabled">
                                </div>
                            </div>
                        </form>
                        </div>`
                ,area:["46%","53%"]
                ,btn: ['提交', '取消']
                ,yes: function(index, layero){
                    if (data != null) {     //添加用户角色
                        let params = {user_id:data.id,role_id:role_id};
                        addUserRoleMethod(params);
                    }
                }
                ,btn2: function(index, layero){

                },
                success: function(layero, index){
                    roles.forEach(item => {
                        let str = `<option value="${item.id}">${item.role_name}</option>`;
                        $("#role_name2").append(str);
                    });
                    form.render();
                    if (data != null){      //修改用户角色

                    }else {         //添加用户角色

                    }
                }
            })
        }

        form.on('select(role_name)', function(data){
            role_id = data.value;
            roles.forEach(item => {
                if (item.id == data.value){
                    $("#role_desc2").val(item.role_desc);
                }
            });
        });

        //增加用户角色请求方法
        function addUserRoleMethod(params) {
            axios.post('/leek_bbs/stair/userRoleManage/insertUserRoles',params).then(response => {
                let data = response.data;
                if (data.msg == "success"){
                    layer.closeAll();
                    ui.success("添加成功",1500,false);
                    tableLoad.reload();
                } else if (data.code == "500036") {
                    layer.closeAll();
                    ui.alert(data.msg,1500,false);
                } else if (data.code == "500037") {
                    layer.msg(data.msg);
                } else {
                    ui.error(data.msg,1500,false);
                }
            }).catch(error => {
                layer.msg("系统出现了一个未知异常");
            })
        }

    });

    //对要输出的时间进行格式化处理
    function formDate(dateStr) {
        var date = new Date(dateStr);
        var y = date.getFullYear();
        var m = (date.getMonth()+1).toString().padStart(2,"0");
        var d = date.getDate().toString().padStart(2,"0");
        var hh = date.getHours();
        var mm = date.getMinutes().toString().padStart(2,"0");
        //使用Es6属性进行字符串拼接
        return `${y}-${m}-${d} ${hh}:${mm}`;
    };

    //增加用户
   function addUser() {
       layui.use(['layer','form'],function () {
           var form = layui.form;
           layer.open({
               type: 1,
               id: 'addUser', //id唯一标识
               title: '添加用户',
               content: `<div style="margin-top: 30px;">
            <form class="layui-form" lay-filter="registerForm">
                <div class="layui-form-item">
                    <label class="layui-form-label">昵称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="another_name" lay-verify="required" autocomplete="off" placeholder="请输入昵称" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="username" lay-verify="required" autocomplete="off" placeholder="请输入用户名" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-inline">
                        <input type="password" name="password" placeholder="请输入密码" lay-verify="required|password" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">确认密码</label>
                    <div class="layui-input-inline">
                        <input type="password" name="pwd" placeholder="请再次输入密码" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">Email</label>
                    <div class="layui-input-inline">
                        <input type="email" name="email" lay-verify="required|email" autocomplete="off" placeholder="请输入邮箱地址" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block" style="margin-bottom: 52px;margin-top: -34px;">
                        <span id="errorRes" style="margin-left:0;font-size: 18px;color: red;"></span>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block" style="margin-top: -40px;">
                      <button type="submit" class="layui-btn btn-bg" lay-submit="" lay-filter="registerBtn">注册</button>
                      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
            </div>`,
               anim: 2,    //动画
               resize: false,  //关闭拉伸
               //scrollbar: false,   //不允许出现滚动条
               area: ['500px', '500px'],
               success: function (layero, index) {
               }
           })
           form.on('submit(registerBtn)',function (data) {
               //alert(JSON.stringify(data.field))
               var data = data.field;
               //console.log(data.field)
               if (data.password != data.pwd) {
                   layer.msg('两次密码不一致', {icon: 5,time: 2000});
               }else {
                   axios.post("/leek_bbs/stair/userManage/addUser",data
                   ).then((response)=>{
                       console.log(response)
                       let resdata =response.data;
                       if (resdata.code == "500020") {     //用户注册成功
                           layer.msg('<img src="/leek_bbs/statics/yu-ui/images/ui-success.png">&emsp;用户注册成功', {
                               time: 2000 //2秒关闭（如果不配置，默认是3秒）
                           }, function(){
                               tableLoad.reload();
                               layer.closeAll();
                           });
                       }else if (resdata.code == "300022"){    //用户存在
                           $("#errorRes").text(resdata.msg);
                       } else {   //用户注册失败
                           layer.msg('<img src="/leek_bbs/statics/yu-ui/images/ui-error.png">&emsp;'+resdata.msg, {
                               time: 3000 //2秒关闭（如果不配置，默认是3秒）
                           });
                       }
                   })
               }
               return false;
           })
           //自定义验证规则  
           form.verify({
               password: [
                   /^[\S]{6,12}$/
                   ,'密码必须6到16位，且不能出现空格'
               ]
               ,phone: [/^1[3|4|5|7|8]\d{9}$/, '手机号格式不对！']
               ,email: [/^[a-z0-9._%-]+@([a-z0-9-]+\.)+[a-z]{2,4}$|^1[3|4|5|7|8]\d{9}$/, '邮箱格式不对']
           });
       })
   }

   //修改用户状态
   function updateUserState(userId,userState){
       axios.get("/leek_bbs/stair/userManage/updateUserState",{
            params: {
                userId: userId,
                userState:userState
            }
        }).then((response)=>{
            var data = response.data;
            if(data.code=="500020") {
                ui.success("用户状态修改成功",1500,true)
                tableLoad.reload();
            }else{
                ui.error(data.msg,1500,true)
            };
            })
        }


    function getRoles(){
        axios.get('/leek_bbs/stair/roleManage/listRole').then(result => {
            roles = result.data;
            roles.forEach(item => {
                let str = `<option value="${item.role_name}">${item.role_name}</option>`;
                $("#role_name").append(str);
            })
        }).catch(error => {
            ui.error("数据请求异常",1500,false);
        })
    }

</script>

</body>
</html>